<template>
    <div class="box">
        <div class="content">
            <div class="login-wrapper">
                <h1>登录</h1>
                <div class="login-form">
                    <div class="username-form-item">
                        <span>用户名</span>
                        <input type="text" class="input-item" v-model="userInfo.username">
                        <p v-if="errors.username" class="p-error">{{ errors.username }}</p>
                    </div>
                    <div class="password-form-item">
                        <span>密码</span>
                        <input type="password" class="input-item" v-model="userInfo.password">
                        <p v-if="errors.password" class="p-error">{{ errors.password }}</p>
                    </div>
                    <el-button color="rgb(59, 72, 89)" :loading="btnLoading" :disabled="btnEnable" class="login-btn" @click="loginSubmit">登录</el-button>
                </div>
                <div class="divider">
                    <span class="line"></span>
                    <div class="divider-text">其他登录方式</div>
                    <span class="line"></span>
                </div>
                <div class="other-login-wrapper">
                    <div class="other-login-item">
                        <img src="@/assets/svg/qq.svg" alt="">
                    </div>
                    <div class="other-login-item">
                        <img src="@/assets/svg/wechat.svg" alt="">
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>


<script setup lang="ts">
import { reactive,watchEffect,ref} from 'vue';
import { doLogin} from '@/api/login';
import type LoginUser from '@/interfaces/LoginUser';
import { getKeyAndPassword } from '@/utils/jsencrypt';
import { nanoid } from 'nanoid';
import Cookies from "js-cookie";
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/useUserStore';

// 变量
const router = useRouter()
const userStore = useUserStore()

// 表单数据
const userInfo = reactive({
    username:"",
    password:"",
    key:"",
    uid:""
})

//校验错误数据
const errors = reactive({
    username:"",
    password:""
})
// 控制提交按钮的禁用状态
const btnEnable = ref(true) //控制按钮禁用
const btnLoading = ref(false) //控制按钮加载样式
const validControl = ref(true) //控制表单校验是否开启

// 函数

// 表单校验
function validateForm(){
    btnEnable.value=true
    if(userInfo.username.trim()===''){
        errors.username='用户名不能为空'
    }else if(!/^[a-zA-Z0-9]{8}$/.test(userInfo.username)){
        errors.username="用户名必须为8位的字母或数字"
    }else{
        errors.username=''
    }

    if(userInfo.password.trim()===''){
        errors.password='密码不能为空'
    }else if(!/^[A-Za-z0-9]{6,}$/.test(userInfo.password)){
        errors.password='密码长度至少为6位'
    }else{
        errors.password=''
    }
    if(errors.username==''&&errors.password==''){
        btnEnable.value=false
    }
}

//监听表单变化,自动校验
watchEffect(()=>{
    if(validControl.value==true){
        validateForm();
    }
})


// 登录
async function loginSubmit() {
    // 1.关闭表单校验
    validControl.value = false
    // 2.开启加载按钮
    btnLoading.value = true
    try{
        // 3.加密
        const keyAndPassword = await getKeyAndPassword(userInfo.password)
        userInfo.key = keyAndPassword[0]
        userInfo.password = keyAndPassword[1]
        // 4.检查UID作为设备唯一标识(un use)
        userInfo.uid = checkUID()
        const json = await doLogin(userInfo)
        if(json.state==200){
            const loginInfo:LoginUser = json.data
            localStorage.setItem("wsw_token",loginInfo.token)
            Object.assign(userStore.user,loginInfo)
            userStore.loginState = true
            ElMessage.success("登录成功!")
            router.push("/")
        }else{
            ElMessage.warning(json.message)
        }
    }catch(err:any){
        ElMessage.error(err)
    }finally{
        // 清空密码
        userInfo.password = ""
    }
    
    btnLoading.value = false
    validControl.value = true
}


/**
 * 检查cookie中登录需要的uid是否存在
 * 不存在则生成一个,存在则直接拿取默认保存15天
 * 值为null或有值时，会有些许问题
 * @returns uid 
 */
 const checkUID = function () {
    let WSWUID = Cookies.get("wsw_uid") as string
    if (!WSWUID) {
        let date = new Date();
        date.setTime(date.getTime() + (60 * 1000 * 60 * 24 * 15));//设置15天后过期
        const uid = nanoid();
        Cookies.set("wsw_uid", uid, { expires: date });
        WSWUID = uid
    }
    return WSWUID;
}

</script>

<style scoped>
*{
    padding: 0;
    margin: 0;
}
/* 公共Css样式 */
.box{
    width: 100vw;
    height: 100vh;
}
h1{
    text-align: center;
}
.form-item{
    margin: 20px 0;
}
.form-item span{
    display: block;
    margin: 5px 20px;
    font-weight: 100;
}
.input-item{
    width: 100%;
    border-radius: 40px;
    padding: 20px;
    box-sizing: border-box;
    font-size: 20px;
    font-weight: 200;
}
.input-item:focus{
    outline: none;
}
.login-btn{
    width: 100%;
    border-radius: 40px;
    color: #fff;
    border: 0;
    font-weight: 100;
    margin-top: 10px;
    cursor: pointer;
}
.divider{
    width: 100%;
    margin: 20px 0;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
}
.divider span:nth-child(1){
    flex: 1;
}
.divider span:nth-child(3){
    flex: 1;
}
.line{
    display: inline-block;
    max-width: 30%;
    width: 30%;
}
.divider-text{
    vertical-align: middle;
    margin: 0px 20px;
    line-height: 0px;
    display: inline-block;
    width: 100px;
}
.other-login-wrapper{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.other-login-item{
    border: 1px solid rgb(214, 222, 228);
    padding: 10px;
    margin: 10px;
}
.p-error{
    color: red;
    font-size: x-small;
}

/* 一般大于手机的尺寸样式 */
@media(min-width: 767px){
    .content{
        width: 85vw;
        height: 90vh;
        background: url('@/assets/img/login_two.jpg') no-repeat;
        background-size: 100% 100%;
        position: absolute;
        right: 15%;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        border-radius: 20px;
        background-color: #fff;
        box-shadow: 0 0 10px;
    }
    .login-wrapper{
        width: 25vw;
        position: absolute;
        right: 15%;
        top: 50%;
        transform: translateY(-50%);
    }
    h1{
        text-align: center;
        font-size: 45px;
        color: rgb(81, 100, 115);
        margin-bottom: 40px;
    }
    .login-form{
        margin: 10px 0;
    }
    .form-item span{
        color: rgb(81, 100, 115);
    }
    .input-item{
        height: 60px;
        border: 1px solid rgb(214, 222, 228);
    }
    .login-btn{
        height: 50px;
        background-color: rgb(59, 72, 89);
    }
    .divider .line{
        border-bottom: 1px solid rgb(214, 222, 228);
    }
    .other-login-item{
        border-radius: 20px;
    }
    .other-login-item img{
        width: 40px;
        height: 40px;
    }
}

/* 手机端样式 */
@media(max-width: 768px){
    .content{
        width: 100vw;
        height: 100vh;
        background: url("@/assets/img/3.jpg") no-repeat;
        background-size: 100% 100%;
        display: flex;
        align-items: flex-start;
        justify-content: center;
    }
    .login-wrapper{
        width: 70%;
        height: 60%;
        padding-top: 15%;
    }
    h1{
        font-size: 30px;
        color: #000000;
    }
    .form-item{
        margin: 10px 0;
    }
    span{
        color: rgb(117, 81, 81);
    }
    .input-item{
        height: 30px;
        border: 1px solid rgb(113, 129, 141);
        /* 透明 */
        /* background-color: transparent;  */
        color: #000000;
    }
    .login-btn{
        height: 40px;
        background-color: rgb(235, 95, 93);
        font-size: 16px;
    }
    .line{
        border-bottom: 1px solid #000000;
    }
    .divider-text{
        color: #8a5d5d;
        font-weight: 100;
    }
    .other-login-item{
        border-radius: 15px;
    }
    img{
        width: 35px;
        height: 35%;
    }
}


</style>